
#include <pthread.h>
#include <sys/types.h>
#include <sys/sem.h>
#include <stdlib.h>
#include <stdio.h>
#include <sys/time.h>
#include <unistd.h>
#include <sys/wait.h>
#include <sys/shm.h>


int selled_tickets = 0;

int semid;	//信号量标识

int total_tickets = 10;   // 票总数



void P(int semid,int index){
	struct sembuf sem;       //对index 信号量执行p
	sem.sem_num = index;
	sem.sem_op = -1;
	sem.sem_flg = 0;
	semop(semid,&sem,1);	//调用semop函数
	return;
}


void V(int semid,int index){
	struct sembuf sem;       // 对index 信号量执行v
	sem.sem_num = index;
	sem.sem_op = 1;
	sem.sem_flg = 0;
	semop(semid,&sem,1);	
	return;
}


void* subp1(void* arg){     //售票进程1
        int count1=0;
	while(1){
		P(semid,0);
                if(total_tickets==0) {
                   printf("%d tickets were sold in process one\n",count1);
                   V(semid,0);
	           return NULL;
                 }
		total_tickets--;
                count1++;
                selled_tickets++;
		printf("Window 1: Selling NO.%d tickets\n",selled_tickets);
		V(semid,0);
                sleep(1);
}

	
}



void* subp2(void* arg){   //售票进程2
        int count2=0;
	while(1){
		P(semid,0);
                
                   if(total_tickets==0) {
                   printf("%d tickets were sold in process one\n",count2);
                   V(semid,0);
	           return NULL;
                 }
		total_tickets--;
                count2++;
                selled_tickets++;
		printf("Window 2: Selling NO.%d tickets\n",selled_tickets);
		V(semid,0);
                sleep(1);
           }
}
int main(){
	semid = semget(IPC_PRIVATE,1,IPC_CREAT|0666);
	semctl(semid,0,SETVAL,1);	
	pthread_t p1,p2;
	int ret1,ret2;
	
	ret1=pthread_create(&p1,NULL,subp1,NULL);
	if(ret1!=0){
		printf("Create pthread1 error!\n");
		exit(1);
	}
		
	ret2=pthread_create(&p2,NULL,subp2,NULL);
	if(ret2!=0){
		printf("Create pthread2 error!\n");
		exit(1);
	}

	pthread_join(p1,NULL);
	pthread_join(p2,NULL);	
	printf("over\n ");
	return 0;
}


